package com.sphd.education.fragments;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.sphd.education.EducationApplication;
import com.sphd.education.R;
import com.sphd.education.activitys.LessonInfoActivity;
import com.sphd.education.activitys.LoginActivity;
import com.sphd.education.adapter.ClassifyAdapter;
import com.sphd.education.adapter.ClassifyTwoAdapter;
import com.sphd.education.adapter.LessonPriceAdapter;
import com.sphd.education.adapter.SearchLessonRecyclerAdapter;
import com.sphd.education.base.BaseFragment;
import com.sphd.education.info.CityGpsInfo;
import com.sphd.education.info.ClassifyOne;
import com.sphd.education.info.ClassifyTwo;
import com.sphd.education.info.EducationIntentKey;
import com.sphd.education.info.LessonInfo;
import com.sphd.education.info.MyInfo;
import com.sphd.education.interfaces.FragmentInterface;
import com.sphd.education.interfaces.RecyclerViewOnClickListener;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.services.LessonSaveService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2015/10/13.
 */
public class SearchLessonFragment extends BaseFragment {
    @Bind(R.id.searchlesson_recycler)
    RecyclerView searchlessonRecycler;
    @Bind(R.id.searchlesson_swiperefresh)
    SwipeRefreshLayout searchlessonSwiperefresh;
    @Bind(R.id.classify_one_textview)
    TextView classifyOneTextview;
    @Bind(R.id.image_classify)
    ImageView imageClassify;
    @Bind(R.id.linearlayou_classify)
    LinearLayout linearlayouClassify;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    @Bind(R.id.image_pirce)
    ImageView imagePirce;
    @Bind(R.id.linearlayou_pirce)
    LinearLayout linearlayouPirce;
    @Bind(R.id.tv_zone)
    TextView tvZone;
    @Bind(R.id.image_zone)
    ImageView imageZone;
    @Bind(R.id.linearlayou_zone)
    LinearLayout linearlayouZone;
    @Bind(R.id.classify_one_linear)
    LinearLayout classifyOneLinear;
    @Bind(R.id.blew_line_one)
    View blewLineOne;
    @Bind(R.id.blew_line_two)
    View blewLineTwo;
    @Bind(R.id.blew_line_three)
    View blewLineThree;
    @Bind(R.id.blew_line)
    LinearLayout blewLine;
    String condition;
    private String Tag = "SearchLessonFragment";
    private FragmentInterface fragmentInterface;
    private View rootView;
    private SearchLessonRecyclerAdapter searchLessonRecyclerAdapter;
    private LinearLayoutManager layoutManager;
    private Context context;
    private List<LessonInfo> lessonInfos;
    private Intent intent;
    private Bundle bundle;
    private String flag;//标志
    public static final int START_SEARCH_LESSON = 1;
    public static final int END_SEARCH_LESSON = 2;
    public static final int REFRESH_SEARCH_LESSON = 3;
    public static final int REFRESH_END_SEARCH_LESSON = 4;
    public static final int START_LESSON_INFO = 5;
    private int pageNumber = 1;
    private int scrollToPosition = 0;
    private boolean isRefreshing = false;
    private String cityName;
    private StringRequest myNetSearchLesson;
    private MyInfo myInfo;
    private List<ClassifyOne> classifyOneList;
    private List<ClassifyTwo> classifyTwoList;
    private ClassifyAdapter classifyAdapter;
    private ClassifyTwoAdapter classifyTwoAdapter;
    private View popuCtnViewClassifyOne;//分类一级菜单
    private PopupWindow optionWindowClassifyone;//分类一级菜单

    private PopupWindow pircePopWindow;
    private View getPopuCtnViewClassifyPrice;
    private ListView classifyPriceListview;
    private List<String> pricelist;
    private LessonPriceAdapter lessonPriceAdapter;
    private LessonPriceAdapter lessonZoneAdapter;

    private PopupWindow zonePopWindow;
    private View getPopuCtnViewClassifyZone;
    private ListView classifyZoneListview;
    private WindowManager wm;//获取屏幕大小
    private ListView classifyOneListview;
    private ListView classifyTwoListview;
    private int wwidth;//屏幕宽高
    private int wheight;
    private String zoneFlag;//用来区分本地定位城市还是切换后的城市的数据库查询
    private Cursor myCursorarea;
    private Cursor myCursorcity;
    private String filepath;
    private SQLiteDatabase db;
    private CityGpsInfo cityGpsInfo;
    private int CitySort;
    private List<String> zonelist;
    TextView allSbj;
    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static SearchLessonFragment newInstance(Bundle bundle) {
        SearchLessonFragment fragment = new SearchLessonFragment();
        fragment.setArguments(bundle);//传值判断是那个fragment
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.e("onCreateView","onCreateView");
        rootView = inflater.inflate(R.layout.fragment_search_lesson, container, false);
        ButterKnife.bind(this, rootView);
        intent = new Intent();
        bundle = new Bundle();
        context = getContext();

        initView();
        initPopuWindow(inflater);
        return rootView;
    }

    private void initPopuWindow(LayoutInflater inflater) {
//        zonelist.add("全部");
        popuCtnViewClassifyOne = inflater.inflate(R.layout.layout_popwindows_classifyone, null);
        getPopuCtnViewClassifyPrice = inflater.inflate(R.layout.layout_popwindows_classprice, null);
        getPopuCtnViewClassifyZone = inflater.inflate(R.layout.layout_popwindows_classzone, null);
        classifyOneListview = (ListView) popuCtnViewClassifyOne.findViewById(R.id.classify_one_listview);
        classifyTwoListview = (ListView) popuCtnViewClassifyOne.findViewById(R.id.classify_two_listview);
        allSbj= (TextView) popuCtnViewClassifyOne.findViewById(R.id.all_sbj);
        classifyOneList = DataSupport.findAll(ClassifyOne.class);
        classifyAdapter = new ClassifyAdapter(context, classifyOneList, R.layout.layout_classify_item);
        classifyOneListview.setAdapter(classifyAdapter);

        classifyPriceListview = (ListView) getPopuCtnViewClassifyPrice.findViewById(R.id.classify_price_listview);
        lessonPriceAdapter = new LessonPriceAdapter(context, pricelist);

        classifyZoneListview = (ListView) getPopuCtnViewClassifyZone.findViewById(R.id.classify_zone_listview);
        lessonZoneAdapter = new LessonPriceAdapter(context, zonelist);
        //分类适配器
        classifyOneListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                classifyAdapter.setSelectedPosition(position);
                classifyAdapter.notifyDataSetInvalidated();
//                Toast.makeText(context, classifyOneList.get(position).getClassify() + classifyOneList.get(position).getId(), Toast.LENGTH_SHORT).show();
                classifyTwoList = DataSupport.where("classifyone_id = ?",
                        "" + classifyOneList.get(position).getSid()).find(ClassifyTwo.class);
                classifyTwoAdapter.notifyDataSetChanged();
                classifyTwoAdapter = new ClassifyTwoAdapter(context, classifyTwoList, R.layout.layout_classify_item);
                classifyTwoListview.setAdapter(classifyTwoAdapter);
            }
        });
        classifyTwoListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                optionWindowClassifyone.dismiss();
                classifyOneTextview.setText(classifyTwoList.get(position).getClassify().toString());
                scrollToPosition = 0;
                lessonInfos.clear();
                pageNumber = 1;
                getLessonHandler.sendEmptyMessageDelayed(START_SEARCH_LESSON, 0);
            }
        });
        allSbj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                classifyOneTextview.setText("全部");
                optionWindowClassifyone.dismiss();
                searchLessonRecyclerAdapter.setHasMoreData(true);
                scrollToPosition = 0;
                lessonInfos.clear();
                pageNumber = 1;
                getLessonHandler.sendEmptyMessageDelayed(START_SEARCH_LESSON, 0);
            }
        });
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        flag = getArguments().getString(EducationIntentKey.FLAG);
        condition= getArguments().getString("condition");
        lessonInfos = new ArrayList<LessonInfo>();
        wm = getActivity().getWindowManager();
        wwidth = wm.getDefaultDisplay().getWidth();
        wheight = wm.getDefaultDisplay().getHeight();
        zonelist = new ArrayList<String>();
        pricelist = new ArrayList<>();
        Log.e("onAttach", "onAttach");
    }

    private void initView() {
        cityGpsInfo = DataSupport.findLast(CityGpsInfo.class);
        myInfo = DataSupport.findLast(MyInfo.class);
        layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);//recyclerview的空间
        searchlessonRecycler.setLayoutManager(layoutManager);
        searchlessonSwiperefresh.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        if (flag.equals(EducationIntentKey.HOMEFLAG)) {
            scrollToPosition = lessonInfos.size();
            if (cityGpsInfo.getLastcity().equals(cityGpsInfo.getOthercity())) {
                getLessonHandler.sendEmptyMessageDelayed(START_SEARCH_LESSON, 0);
            } else {
                scrollToPosition = 0;
                lessonInfos.clear();
                pageNumber = 1;
                getLessonHandler.sendEmptyMessageDelayed(START_SEARCH_LESSON, 0);
            }
        } else if (flag.equals(EducationIntentKey.HISTORY)) {
            classifyOneLinear.setVisibility(View.GONE);
            blewLine.setVisibility(View.GONE);
            lessonInfos = DataSupport.findAll(LessonInfo.class);
            Collections.reverse(lessonInfos);
            getLessonHandler.sendEmptyMessageDelayed(END_SEARCH_LESSON, 0);
        } else if (flag.equals(EducationIntentKey.COLLECT)) {
            classifyOneLinear.setVisibility(View.GONE);
            blewLine.setVisibility(View.GONE);
            if (myInfo == null || myInfo.getUserid() == 0) {
                intent.setClass(context, LoginActivity.class);
                startActivity(intent);
            } else {
                selectCollect();
            }
        }else if (flag.equals(EducationIntentKey.SEARCH_LESSON_TAG)){
            addSearchLesson();
        }
        searchLessonRecyclerAdapter = new SearchLessonRecyclerAdapter(lessonInfos, R.layout.layout_item_lesson);
        searchlessonRecycler.setAdapter(searchLessonRecyclerAdapter);
        myListener();

    }

    private void addSearchLesson() {
        showMyDialog();
        String myurl=EducationUrl.HttpTitle+EducationUrl.SearchSchoolorLesson+"type=2&condition="+condition;
        Log.e("myurl", myurl);
        StringRequest stringRequest =new StringRequest(myurl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("response",response);
                        getList(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("error",error.toString());
            }
        });
        EducationApplication.getRequestQueue().add(stringRequest);
    }

    private void myListener() {
        //列表单个监听
        searchLessonRecyclerAdapter.setRecyclerViewOnClickListener(new RecyclerViewOnClickListener() {
            @Override
            public void onTouch(View view, int position) {
                switch (view.getId()) {
                    case R.id.lesson_card:
                        Message message = getLessonHandler.obtainMessage();
                        message.what = START_LESSON_INFO;
                        message.arg1 = lessonInfos.get(position).getLesson_id();
                        getLessonHandler.sendMessage(message);
                        if (flag.equals(EducationIntentKey.HOMEFLAG)) {
                            Intent intentservice = new Intent(context, LessonSaveService.class);
                            bundle.putInt("falg",1);
                            bundle.putSerializable("lessoninfo", lessonInfos.get(position));
                            intentservice.putExtra("lesson", bundle);
                            getContext().startService(intentservice);
                        }
                        break;
                    case R.id.loadin_button:
                        //加载的过度效果添加
                        scrollToPosition = lessonInfos.size();//加载完跳转到那个位置
                        searchLessonRecyclerAdapter.setHasMoreData(true);
                        getLessonHandler.sendEmptyMessageDelayed(START_SEARCH_LESSON, 0);
                        break;
                    default:
                        break;

                }

            }
        });

        //刷新控件的监听
        searchlessonSwiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (flag.equals(EducationIntentKey.HOMEFLAG)) {
                    searchLessonRecyclerAdapter.setHasMoreData(true);
                    pageNumber = 1;
                    scrollToPosition = 0;
                    getLessonHandler.sendEmptyMessageDelayed(REFRESH_SEARCH_LESSON, 0);
                } else if (flag.equals(EducationIntentKey.COLLECT)) {
                    lessonInfos.clear();
                    selectCollect();
                } else {
                    searchlessonSwiperefresh.setRefreshing(false);
                }
            }
        });
    }

    private void getLessonInfo(final int lesson_id) {
        bundle.putInt("lessonId", lesson_id);
        bundle.putString(EducationIntentKey.FLAG, flag);
        intent.putExtra(EducationIntentKey.LESSON, bundle);
        intent.setClass(context, LessonInfoActivity.class);
        startActivity(intent);

    }

    //查询数据库中收藏的学校本地版本
    private void selectCollect() {
        showMyDialog();
        StringRequest collextStringRequest = new StringRequest(Request.Method.POST,
                EducationUrl.HttpTitle + EducationUrl.MyCollect,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("shoucang",response);
                        lessonInfos.clear();
                        getList(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissMyDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();

                map.put("memberId", myInfo.getUserid() + "");
                map.put("type", "2");
                return map;
            }
        };
        collextStringRequest.setTag("collectlesson");
        EducationApplication.getRequestQueue().add(collextStringRequest);
        getLessonHandler.sendEmptyMessageDelayed(END_SEARCH_LESSON, 0);
    }

    @Override
    public void myNet() {
        showMyDialog();
        myNetSearchLesson = new StringRequest(Request.Method.POST,
                EducationUrl.HttpTitle + EducationUrl.SearchLesson,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        getList(response);
                        Log.e("课", response);
                    }
                }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("error",error.toString());
                EducationUrl.showToast(context, error.toString());
                dismissMyDialog();
                searchlessonSwiperefresh.setRefreshing(false);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageNumber", pageNumber + "");
                cityGpsInfo = DataSupport.findLast(CityGpsInfo.class);
                if (cityGpsInfo.isQiecity()) {
                    cityName = cityGpsInfo.getOthercity();
                } else {
                    cityName = cityGpsInfo.getLoacalcity();
                }
                map.put("city", cityName);
                if (!classifyOneTextview.getText().equals("类目")&&!classifyOneTextview.getText().equals("全部")){
                    map.put("category",classifyOneTextview.getText().toString());
                }
                if (!tvPrice.getText().equals("价格")&&!tvPrice.getText().equals("全部")){
                    if (tvPrice.getText().equals("低于1000元")){
                        map.put("price1", String.valueOf(0.0));
                        map.put("price2", String.valueOf(1000.0));
                    }else if (tvPrice.getText().equals("1000元-2000元")){
                        map.put("price1", String.valueOf(1000.0));
                        map.put("price2", String.valueOf(2000.0));
                    }else if (tvPrice.getText().equals("2000元以上")){
                        map.put("price1", String.valueOf(2000.0));
                        map.put("price2", String.valueOf(2000000000000.0));
                    }
                }
                EducationUrl.showLog(map.toString());
                Log.e("map", map.toString() + "");
                return map;
            }
        };
        myNetSearchLesson.setRetryPolicy(new DefaultRetryPolicy(4 * 1000, 3, 1.0f));
        myNetSearchLesson.setTag(EducationIntentKey.SEARCH_LESSON_TAG);
        EducationApplication.getRequestQueue().add(myNetSearchLesson);
    }


    @Override
    public void getList(String string) {
        try {
            if (string.equals("[]")) {
                isRefreshing = false;
                searchLessonRecyclerAdapter.setHasMoreData(false);
                getLessonHandler.sendEmptyMessageDelayed(END_SEARCH_LESSON, 0);
                searchlessonSwiperefresh.setRefreshing(false);
                dismissMyDialog();
                return;
            }

            JSONArray jsonArray = new JSONArray(string);
            if (flag.equals(EducationIntentKey.HOMEFLAG)) {
                if (jsonArray.length() == 8) {
                    isRefreshing = true;
                    searchLessonRecyclerAdapter.setHasMoreData(true);
                } else {
                    isRefreshing = false;
                    searchLessonRecyclerAdapter.setHasMoreData(false);
                }
            } else if (flag.equals(EducationIntentKey.COLLECT)) {
                isRefreshing = false;
                searchLessonRecyclerAdapter.setHasMoreData(false);
                searchlessonSwiperefresh.setRefreshing(false);
            }else {
                searchLessonRecyclerAdapter.setHasMoreData(false);
                searchlessonSwiperefresh.setRefreshing(false);
            }

            EducationUrl.showLog(string);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                LessonInfo lessonInfo = new LessonInfo();
                if (jsonObject.has("id"))
                    lessonInfo.setLesson_id(jsonObject.getInt("id"));
                if (jsonObject.has("lessonName"))
                    lessonInfo.setName(jsonObject.getString("lessonName"));
                if (jsonObject.has("startDate")) {
                    String a = jsonObject.getString("startDate");
                    String c = a.replaceAll("-", ".");
                    Log.e("c", c + "");
                    String[] strs = c.split("[ ]");
                    lessonInfo.setBeginTime(strs[0].toString());
                }
                if (jsonObject.has("realTuition"))
                    lessonInfo.setRealTuition(jsonObject.getString("realTuition"));
                if (jsonObject.has("logoPath"))
                    lessonInfo.setImage(jsonObject.getString("logoPath"));
                if (jsonObject.has("CUM"))
                    lessonInfo.setAds(jsonObject.getString("CUM"));
                if (jsonObject.has("organization")) {
                    JSONObject schoolJson = new JSONObject(jsonObject.getString("organization"));
                    if (schoolJson.has("name"))
                        lessonInfo.setSchoolName(schoolJson.getString("name"));
                    if (schoolJson.has("id"))
                        lessonInfo.setSchoolid(schoolJson.getInt("id"));
                    //此方法制作暂时解决 我的收藏中“课程”不显示地域的问题
                    if (flag.equals(EducationIntentKey.COLLECT)) {
                        if (schoolJson.has("cityAndCounty"))
                            lessonInfo.setSchoolArea(schoolJson.getString("cityAndCounty"));
                    }
                    if (schoolJson.has("area")) {
                        JSONObject areaJsonObject = new JSONObject(schoolJson.getString("area"));
                        if (areaJsonObject.has("name")) {
                            lessonInfo.setSchoolArea(areaJsonObject.getString("name"));
                        }
                    }
                }
                lessonInfos.add(lessonInfo);
            }
            getLessonHandler.sendEmptyMessageDelayed(END_SEARCH_LESSON, 0);
            dismissMyDialog();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getList(JSONObject jsonObject) {
    }

    @Override
    public void getList(JSONArray jsonArray) {

    }

    Handler getLessonHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case START_SEARCH_LESSON:
                    myNet();
                    break;
                case END_SEARCH_LESSON:
                    if (flag.equals(EducationIntentKey.HISTORY)) {
                        searchlessonSwiperefresh.setRefreshing(false);
                        searchlessonRecycler.setAdapter(searchLessonRecyclerAdapter);
                        searchLessonRecyclerAdapter.setHasMoreData(false);
                    } else {
                        pageNumber++;
                        searchlessonSwiperefresh.setRefreshing(false);
                        searchlessonRecycler.setAdapter(searchLessonRecyclerAdapter);
                        searchlessonRecycler.scrollToPosition(scrollToPosition);
                    }
                    break;
                case REFRESH_SEARCH_LESSON:
                    lessonInfos.clear();
                    pageNumber = 1;
                    scrollToPosition = 0;
                    myNet();
                    break;
                case REFRESH_END_SEARCH_LESSON:
                    pageNumber++;
                    searchlessonSwiperefresh.setRefreshing(false);
                    searchlessonRecycler.setAdapter(searchLessonRecyclerAdapter);
                    searchlessonRecycler.scrollToPosition(scrollToPosition);
                    break;
                case START_LESSON_INFO:
                    getLessonInfo(msg.arg1);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.linearlayou_classify)
    public void setOnClickClassifyOne() {
        imageClassify.setImageResource(R.mipmap.xiangshangjiantou);
        showPopWindowsOne();
    }

    @OnClick(R.id.linearlayou_pirce)
    public void setOnClickClassifyPrice() {
        imagePirce.setImageResource(R.mipmap.xiangshangjiantou);
        showPircePopWindow();
    }

    @OnClick(R.id.linearlayou_zone)
    public void setOnClickClassifyZone() {
        imageZone.setImageResource(R.mipmap.xiangshangjiantou);
        showZonePopWindow();
    }

    //显示一级分类的popwindow
    private void showPopWindowsOne() {
        blewLineOne.setBackgroundColor(context.getResources().getColor(R.color.main_bottom_up));
        if (null == optionWindowClassifyone) {
            optionWindowClassifyone = new PopupWindow(popuCtnViewClassifyOne,
                    wwidth, wheight / 2);
            optionWindowClassifyone.setFocusable(true);
            optionWindowClassifyone.setBackgroundDrawable(new BitmapDrawable());
        }
        optionWindowClassifyone.showAsDropDown(linearlayouClassify, 0, 5);
        classifyAdapter.setSelectedPosition(0);

        classifyTwoList = DataSupport.where("classifyone_id = ?",
                "" + classifyOneList.get(0).getSid()).find(ClassifyTwo.class);
        classifyTwoAdapter = new ClassifyTwoAdapter(context, classifyTwoList, R.layout.layout_classify_item);
        classifyTwoListview.setAdapter(classifyTwoAdapter);

        optionWindowClassifyone.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                blewLineOne.setBackgroundColor(context.getResources().getColor(R.color.my_gr));
                imageClassify.setImageResource(R.mipmap.xiangxiajiantou);
            }
        });
    }

    //显示价格popwindow
    private void showPircePopWindow() {
        blewLineTwo.setBackgroundColor(context.getResources().getColor(R.color.main_bottom_up));
        if (pircePopWindow == null) {
            if (pricelist.size() > 10) {
                pircePopWindow = new PopupWindow(getPopuCtnViewClassifyPrice, wwidth, wheight / 2);
            } else {
                pircePopWindow = new PopupWindow(getPopuCtnViewClassifyPrice, wwidth, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
            pircePopWindow.setFocusable(true);
            pircePopWindow.setBackgroundDrawable(new BitmapDrawable());
        }
        pircePopWindow.showAsDropDown(linearlayouPirce, 0, 5);
        pircePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                blewLineTwo.setBackgroundColor(context.getResources().getColor(R.color.my_gr));
                imagePirce.setImageResource(R.mipmap.xiangxiajiantou);
            }
        });
    }

    private void showZonePopWindow() {
        blewLineThree.setBackgroundColor(context.getResources().getColor(R.color.main_bottom_up));
        Log.e("zonelist.size()", zonelist.size() + "");
        if (zonelist.size() > 10) {
            zonePopWindow = new PopupWindow(getPopuCtnViewClassifyZone, wwidth, wheight / 2);
        } else {
            zonePopWindow = new PopupWindow(getPopuCtnViewClassifyZone, wwidth, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        zonePopWindow.setFocusable(true);
        zonePopWindow.setBackgroundDrawable(new BitmapDrawable());
        zonePopWindow.showAsDropDown(linearlayouZone, 0, 5);
        zonePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                blewLineThree.setBackgroundColor(context.getResources().getColor(R.color.my_gr));
                imageZone.setImageResource(R.mipmap.xiangxiajiantou);
            }
        });
    }

    @Override
    public void onStart() {
        Log.e(Tag, "onStart");
        super.onStart();
        zonelist.clear();
        pricelist.clear();
        zonelist.add("全部");
        cityGpsInfo = DataSupport.findLast(CityGpsInfo.class);
        if (cityGpsInfo.isQiecity()) {
            zoneFlag = cityGpsInfo.getOthercity();
            filepath = "/data/data/" + context.getPackageName() + "/databases/china_province_city_zone.db";
            db = SQLiteDatabase.openDatabase(filepath, null, SQLiteDatabase.OPEN_READWRITE);
            myCursorcity = db.rawQuery("select * from T_City where CityName=\"" + zoneFlag
                    + "\"", null);//是系统里的表
            if (myCursorcity != null) {
                getActivity().startManagingCursor(myCursorcity);
            }
            while (myCursorcity.moveToNext()) {
                CitySort = myCursorcity.getInt(myCursorcity.getColumnIndex("CitySort"));
//                citylist.add(myCursorcity.getString(myCursorcity.getColumnIndex("CityName")));
            }


            myCursorarea = db.rawQuery("select * from T_Zone where CityID=" + CitySort, null);//是系统里的表

            if (myCursorarea != null) {
//                zonelist.clear();
                getActivity().startManagingCursor(myCursorarea);
            }
            while (myCursorarea.moveToNext()) {

                zonelist.add(myCursorarea.getString(myCursorarea.getColumnIndex("ZoneName")));
            }
        } else {
            zoneFlag = cityGpsInfo.getLoacalcity();

            filepath = "/data/data/" + context.getPackageName() + "/databases/china_province_city_zone.db";

            db = SQLiteDatabase.openDatabase(filepath, null, SQLiteDatabase.OPEN_READWRITE);
            myCursorcity = db.rawQuery("select * from T_City where CityName=\"" + zoneFlag
                    + "\"", null);//是系统里的表
            if (myCursorcity != null) {
                getActivity().startManagingCursor(myCursorcity);
            }
            while (myCursorcity.moveToNext()) {
                CitySort = myCursorcity.getInt(myCursorcity.getColumnIndex("CitySort"));
            }


            myCursorarea = db.rawQuery("select * from T_Zone where CityID=" + CitySort, null);//是系统里的表

            if (myCursorarea != null) {
                getActivity().startManagingCursor(myCursorarea);
            }
            while (myCursorarea.moveToNext()) {
                zonelist.add(myCursorarea.getString(myCursorarea.getColumnIndex("ZoneName")));
            }
        }

        pricelist.add("全部");
        pricelist.add("低于1000元");
        pricelist.add("1000元-2000元");
        pricelist.add("2000元以上");
        classifyPriceListview.setAdapter(lessonPriceAdapter);
        classifyPriceListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tvPrice.setText(pricelist.get(position));
                pircePopWindow.dismiss();
                scrollToPosition = 0;
                lessonInfos.clear();
                pageNumber = 1;
                getLessonHandler.sendEmptyMessageDelayed(START_SEARCH_LESSON, 0);
            }
        });
        classifyZoneListview.setAdapter(lessonZoneAdapter);
        classifyZoneListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tvZone.setText(zonelist.get(position));
                zonePopWindow.dismiss();
            }
        });
    }
}
